package com.zlyx.easy.swagger.scanner;

import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSON;
import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.core.utils.HostUtils;
import com.zlyx.easy.core.utils.LogUtils;
import com.zlyx.easy.core.utils.RestUtils;
import com.zlyx.easy.swagger.config.ApiCache;
import com.zlyx.easy.swagger.config.ApiConfiguration.ApiProperties;

/**
 * @description 注册docket
 * @author zhaoguang
 * @date 2019年6月21日
 */
@SpringBean(todo = { "加载并注册docket" })
@EnableScheduling
public class SwaggerScanner extends AbstractSwaggerScanner implements BeanFactoryAware, InitializingBean {

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		listableBeanFactory = (DefaultListableBeanFactory) beanFactory;
		List<ApiProperties> apiProperties = apiConfiguration.getApiProperties();
		if (apiConfiguration.isEnabled() && !apiProperties.isEmpty()) {
			for (ApiProperties api : apiProperties) {
				registerDocket(api.getGroupName(), api);
			}
		}
	}

	@Scheduled(cron = "${easy.swagger.cron:0 0/30 * * * ?}")
	public void scan() {
		List<String> urls = apiConfiguration.getUrls();
		if (Ops.isNotNull(urls)) {
			LogUtils.debug("即将聚合文档，请等待...");
			for (String url : urls) {
				if (!url.endsWith("/")) {
					url = url + "/";
				}
				if (!HostUtils.isCurrentServcer(url)) {
					LogUtils.debug("正在聚合文档地址" + url);
					ApiCache.addApis(RestUtils.postForObject(url + "easy-swagger/apis/get", null));
				}
			}
			LogUtils.debug("聚合文档已完成。");
		}
	}

	@Override
	public void doOnRefreshed(ApplicationContext context) {
		ApiCache.addApis(apiConfiguration.getHost(), documentationCache.all().keySet());
		if (Ops.isNotEmpty(apiConfiguration.getManagerUrl())
				&& !HostUtils.isCurrentServcer(apiConfiguration.getManagerUrl()) && ApiCache.getApis().size() > 0) {
			LogUtils.debug("正在注册文档到聚合服务，请等待...");
			LogUtils.debug("注册聚合服务地址: " + apiConfiguration.getManagerUrl() + "easy-swagger/apis/register");
			RestUtils.postForObject(apiConfiguration.getManagerUrl() + "easy-swagger/apis/register",
					JSON.toJSONString(ApiCache.getApis()));
			LogUtils.debug("注册文档到聚合服务已完成");
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		scan();
	}

}
